﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;
using System.Web;

namespace BugClient
{
    public partial class AssignForm : Form
    {
        WebClient web;
        string url;
        string token;
        string bugID;
        List<string> userList = new List<string>();
        bool isActivate;

        public AssignForm(WebClient web, string url, string token, string bugID, string assignedTo, string[] users, Dictionary<string, string> userDict, bool isActivate)
        {
            InitializeComponent();

            Text = (isActivate ? "激活-" : "指派-") + bugID;
            this.web = web;
            this.url = url;
            this.token = token;
            this.bugID = bugID;
            this.isActivate = isActivate;
            userList.AddRange(users);
            foreach (var user in userList)
            {
                assignBox.Items.Add(userDict[user]);
            }
            assignBox.SelectedIndex = isActivate ? 0 : userList.IndexOf(assignedTo);
        }

        private async void commitButton_Click(object sender, EventArgs e)
        {
            if (web.IsBusy)
                return;
            if (assignBox.SelectedIndex < 0)
            {
                MessageBox.Show("请选择指派目标");
                return;
            }
            string response;
            try
            {
                response = await web.UploadStringTaskAsync(url + (isActivate ? "/activate" : "/assign"), string.Format("bug={0}&assign={1}&comment={2}&token={3}", bugID, userList[assignBox.SelectedIndex], HttpUtility.UrlEncode(commentBox.Text), token));
            }
            catch (WebException ex)
            {
                MessageBox.Show("连接服务器失败：" + ex.Message);
                return;
            }
            if (string.IsNullOrEmpty(response))
            {
                MessageBox.Show("操作失败");
                return;
            }
            DialogResult = DialogResult.OK;
            Dispose();
            Close();
        }
    }
}
